import React, { useState, useEffect } from 'react';
import { 
  Typography, 
  Card, 
  Form, 
  Select, 
  Button, 
  Space, 
  Radio, 
  InputNumber,
  Spin,
  Divider,
  Row,
  Col,
  Tag,
  Progress,
  List,
  Timeline,
  Empty,
  Alert,
  Collapse,
  Table,
  message,
  Tooltip
} from 'antd';
import {
  BarChartOutlined,
  CalendarOutlined,
  WarningOutlined,
  LoadingOutlined,
  LineChartOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  MinusOutlined,
  InfoCircleOutlined,
  QuestionCircleOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import { ShieldOutlined, Statistic } from '../components/icons/IconComponents';
import puaService from '../api/puaService';
import contactsService from '../api/contactsService';

const { Title, Paragraph, Text } = Typography;
const { Option } = Select;
const { Panel } = Collapse;

const PUAConversationAnalysisPage = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [contacts, setContacts] = useState([]);
  const [sessions, setSessions] = useState([]);
  
  useEffect(() => {
    const fetchData = async () => {
      try {
        // 模拟数据获取
        setTimeout(() => {
          setContacts([
            { id: 1, name: '张三', avatar: 'https://via.placeholder.com/40' },
            { id: 2, name: '李四', avatar: 'https://via.placeholder.com/40' },
            { id: 3, name: '王五', avatar: 'https://via.placeholder.com/40' }
          ]);
          
          setSessions([
            { id: 101, name: '工作群', type: 'group', avatar: 'https://via.placeholder.com/40' },
            { id: 102, name: '家庭群', type: 'group', avatar: 'https://via.placeholder.com/40' }
          ]);
        }, 500);
        
        // 实际API调用示例
        // const contactsData = await contactsService.getContacts();
        // const sessionsData = await chatService.getSessions();
        // setContacts(contactsData);
        // setSessions(sessionsData);
      } catch (error) {
        console.error('获取联系人和会话数据失败:', error);
        message.error('获取联系人和会话数据失败');
      }
    };
    
    fetchData();
  }, []);
  
  const handleSubmit = async (values) => {
    setLoading(true);
    setResult(null);
    
    try {
      console.log("提交参数:", values);
      
      // 模拟API调用
      setTimeout(() => {
        const mockResult = {
          "timeframe": values.timeframe,
          "relationship_context": values.relationshipContext,
          "message_statistics": {
            "total_analyzed": 240,
            "total_pua_detected": 36,
            "pua_ratio": 0.15
          },
          "daily_analysis": [
            {
              "date": "2023-08-01",
              "count": 23,
              "pua_statistics": {
                "total_messages": 23,
                "pua_messages": 3,
                "categories": {
                  "gaslighting": 2,
                  "negging": 1
                },
                "severity_sum": 1.5,
                "avg_severity": 0.5
              },
              "detected_pua_messages": [
                {
                  "message_id": 12345,
                  "content": "你总是想太多，我没有那个意思",
                  "detection_result": {
                    "is_pua": true,
                    "score": 0.7,
                    "risk_level": "medium",
                    "detected_patterns": [
                      {
                        "category": "gaslighting",
                        "description": "让对方怀疑自己的感受和判断",
                        "severity": 0.7
                      }
                    ]
                  }
                }
              ]
            },
            {
              "date": "2023-08-05",
              "count": 18,
              "pua_statistics": {
                "total_messages": 18,
                "pua_messages": 5,
                "categories": {
                  "gaslighting": 2,
                  "love_bombing": 1,
                  "guilt_tripping": 2
                },
                "severity_sum": 3.5,
                "avg_severity": 0.7
              },
              "detected_pua_messages": [
                {
                  "message_id": 12346,
                  "content": "我做了这么多你居然还怀疑我，真让人伤心",
                  "detection_result": {
                    "is_pua": true,
                    "score": 0.8,
                    "risk_level": "medium",
                    "detected_patterns": [
                      {
                        "category": "guilt_tripping",
                        "description": "制造罪恶感来控制对方行为",
                        "severity": 0.8
                      }
                    ]
                  }
                }
              ]
            },
            {
              "date": "2023-08-10",
              "count": 31,
              "pua_statistics": {
                "total_messages": 31,
                "pua_messages": 8,
                "categories": {
                  "gaslighting": 3,
                  "love_bombing": 2,
                  "guilt_tripping": 3
                },
                "severity_sum": 6.4,
                "avg_severity": 0.8
              },
              "detected_pua_messages": [
                {
                  "message_id": 12347,
                  "content": "如果你真的爱我，就不会这样对我",
                  "detection_result": {
                    "is_pua": true,
                    "score": 0.9,
                    "risk_level": "high",
                    "detected_patterns": [
                      {
                        "category": "guilt_tripping",
                        "description": "制造罪恶感来控制对方行为",
                        "severity": 0.9
                      }
                    ]
                  }
                }
              ]
            }
          ],
          "trend_analysis": {
            "total_days": 3,
            "total_messages": 72,
            "total_pua_messages": 16,
            "overall_categories": {
              "gaslighting": 7,
              "love_bombing": 3,
              "guilt_tripping": 5,
              "negging": 1
            },
            "top_categories": [
              { "category": "gaslighting", "count": 7 },
              { "category": "guilt_tripping", "count": 5 },
              { "category": "love_bombing", "count": 3 },
              { "category": "negging", "count": 1 }
            ],
            "progression": "escalating"
          },
          "recommendations": {
            "relationship_specific_advice": "在约会关系中，PUA话术往往从微妙的赞美和关注开始，逐渐转向控制和贬低。关注这种模式的变化是很重要的。",
            "suggested_actions": [
              "PUA模式呈现上升趋势，建议提高警惕，并考虑设立更明确的界限",
              "记录不舒适的互动，以便识别模式",
              "考虑咨询专业人士以获取针对性支持"
            ]
          }
        };
        
        setResult(mockResult);
        setLoading(false);
      }, 2000);
      
      // 实际API调用示例
      // const params = {
      //   contact_id: values.contactId,
      //   session_id: values.sessionId,
      //   timeframe: values.timeframe,
      //   message_limit: values.messageLimit,
      //   relationship_context: values.relationshipContext
      // };
      // const response = await puaService.analyzeConversation(params);
      // setResult(response.data);
    } catch (error) {
      console.error('分析对话失败:', error);
      message.error('分析对话失败，请稍后重试');
      setLoading(false);
    }
  };
  
  // 获取趋势图标
  const getTrendIcon = (progression) => {
    switch(progression) {
      case 'escalating': 
        return <ArrowUpOutlined style={{ color: '#ff4d4f' }} />;
      case 'decreasing': 
        return <ArrowDownOutlined style={{ color: '#52c41a' }} />;
      default: 
        return <MinusOutlined style={{ color: '#1890ff' }} />;
    }
  };
  
  // 获取趋势文本
  const getTrendText = (progression) => {
    switch(progression) {
      case 'escalating': 
        return <Text type="danger">上升趋势</Text>;
      case 'decreasing': 
        return <Text type="success">下降趋势</Text>;
      default: 
        return <Text type="secondary">保持稳定</Text>;
    }
  };
  
  // 获取风险等级标签
  const getRiskTag = (level) => {
    const colors = {
      high: 'red',
      medium: 'orange',
      low: 'green',
      none: 'default'
    };
    
    const icons = {
      high: <WarningOutlined />,
      medium: <InfoCircleOutlined />,
      low: <CheckCircleOutlined />,
      none: <CheckCircleOutlined />
    };
    
    const texts = {
      high: '高风险',
      medium: '中等风险',
      low: '低风险',
      none: '无风险'
    };
    
    return (
      <Tag color={colors[level]}>
        {icons[level]}
        <span style={{ marginLeft: 4 }}>{texts[level]}</span>
      </Tag>
    );
  };
  
  // 获取时间范围文本
  const getTimeframeText = (timeframe) => {
    switch(timeframe) {
      case 'recent': return '最近消息';
      case 'last_week': return '最近一周';
      case 'last_month': return '最近一个月';
      default: return '全部消息';
    }
  };
  
  // 获取类别名称
  const getCategoryName = (category) => {
    const categories = {
      gaslighting: '煤气灯效应',
      love_bombing: '爱情轰炸',
      negging: '负面评价',
      isolation: '隔离控制',
      triangulation: '三角关系',
      silent_treatment: '冷暴力',
      guilt_tripping: '罪恶感操纵',
      breadcrumbing: '面包屑喂养',
      other: '其他'
    };
    
    return categories[category] || category;
  };
  
  return (
    <div className="pua-conversation-analysis-page">
      <Title level={2}>
        <Space>
          <ShieldOutlined />
          对话历史PUA分析
        </Space>
      </Title>
      <Paragraph>
        分析您的聊天历史，识别潜在的PUA模式和趋势，帮助您更好地了解对话中的互动动态。
      </Paragraph>
      
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            timeframe: 'all',
            relationshipContext: 'friendship',
            messageLimit: 200
          }}
        >
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                label="选择联系人"
                extra="选择联系人或会话群组"
              >
                <Row gutter={8}>
                  <Col flex="auto">
                    <Form.Item
                      name="contactId"
                      noStyle
                    >
                      <Select 
                        placeholder="选择联系人" 
                        allowClear
                        style={{ width: '100%' }}
                        onChange={() => form.setFieldsValue({ sessionId: undefined })}
                      >
                        {contacts.map(contact => (
                          <Option key={contact.id} value={contact.id}>{contact.name}</Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col flex="auto">
                    <Form.Item
                      name="sessionId"
                      noStyle
                    >
                      <Select 
                        placeholder="选择会话群组" 
                        allowClear
                        style={{ width: '100%' }}
                        onChange={() => form.setFieldsValue({ contactId: undefined })}
                      >
                        {sessions.map(session => (
                          <Option key={session.id} value={session.id}>{session.name}</Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>
                </Row>
              </Form.Item>
            </Col>
            
            <Col xs={24} md={12}>
              <Form.Item
                name="relationshipContext"
                label={
                  <span>
                    关系背景 
                    <Tooltip title="您与分析对象的关系类型">
                      <QuestionCircleOutlined style={{ marginLeft: 4 }} />
                    </Tooltip>
                  </span>
                }
              >
                <Select>
                  <Option value="dating">约会/恋爱关系</Option>
                  <Option value="friendship">朋友关系</Option>
                  <Option value="professional">职场关系</Option>
                  <Option value="family">家庭关系</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                name="timeframe"
                label="时间范围"
              >
                <Radio.Group>
                  <Radio value="all">全部</Radio>
                  <Radio value="recent">最近消息</Radio>
                  <Radio value="last_week">最近一周</Radio>
                  <Radio value="last_month">最近一个月</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            
            <Col xs={24} md={12}>
              <Form.Item
                name="messageLimit"
                label="分析消息数量上限"
                tooltip="最多分析的消息数量，影响分析深度和时间"
              >
                <InputNumber 
                  min={50} 
                  max={500} 
                  style={{ width: '100%' }}
                  addonAfter="条消息"
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              icon={<BarChartOutlined />} 
              loading={loading}
              disabled={!(form.getFieldValue('contactId') || form.getFieldValue('sessionId'))}
              block
            >
              开始分析
            </Button>
          </Form.Item>
        </Form>
      </Card>
      
      {loading && (
        <div style={{ textAlign: 'center', margin: '40px 0' }}>
          <Spin indicator={<LoadingOutlined style={{ fontSize: 36 }} spin />} />
          <p style={{ marginTop: 16 }}>正在深度分析对话历史，请稍候...</p>
        </div>
      )}
      
      {result && (
        <div style={{ marginTop: 24 }}>
          <Row gutter={[24, 24]}>
            {/* 统计概览 */}
            <Col xs={24}>
              <Card title="统计概览">
                <Row gutter={[16, 16]}>
                  <Col xs={24} sm={8}>
                    <Statistic 
                      title="分析消息总数" 
                      value={result.message_statistics.total_analyzed} 
                      suffix="条"
                    />
                  </Col>
                  <Col xs={24} sm={8}>
                    <Statistic 
                      title="检测到PUA内容" 
                      value={result.message_statistics.total_pua_detected} 
                      suffix="条"
                      valueStyle={{ color: result.message_statistics.total_pua_detected > 0 ? '#ff4d4f' : '#3f8600' }}
                    />
                  </Col>
                  <Col xs={24} sm={8}>
                    <Statistic 
                      title="PUA内容占比" 
                      value={Math.round(result.message_statistics.pua_ratio * 100)} 
                      suffix="%"
                      valueStyle={{ color: result.message_statistics.pua_ratio > 0.1 ? '#ff4d4f' : '#3f8600' }}
                    />
                    <Progress 
                      percent={Math.round(result.message_statistics.pua_ratio * 100)}
                      status={result.message_statistics.pua_ratio > 0.1 ? "exception" : "success"}
                      showInfo={false}
                      strokeWidth={5}
                      style={{ marginTop: 8 }}
                    />
                  </Col>
                </Row>
                
                <Divider />
                
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space align="center">
                    <CalendarOutlined />
                    <Text strong>时间范围:</Text>
                    <Text>{getTimeframeText(result.timeframe)}</Text>
                  </Space>
                  
                  <Space align="center">
                    <LineChartOutlined />
                    <Text strong>PUA趋势:</Text>
                    {getTrendIcon(result.trend_analysis.progression)}
                    {getTrendText(result.trend_analysis.progression)}
                  </Space>
                </Space>
              </Card>
            </Col>
            
            {/* 主要PUA类别 */}
            <Col xs={24} md={12}>
              <Card title="主要PUA类别" bodyStyle={{ padding: '0 24px' }}>
                {result.trend_analysis.top_categories.length > 0 ? (
                  <List
                    dataSource={result.trend_analysis.top_categories}
                    renderItem={item => (
                      <List.Item
                        extra={
                          <Tag color="blue">{item.count}次</Tag>
                        }
                      >
                        <List.Item.Meta
                          title={getCategoryName(item.category)}
                          description={item.description}
                        />
                      </List.Item>
                    )}
                  />
                ) : (
                  <Empty description="未检测到PUA模式" />
                )}
              </Card>
            </Col>
            
            {/* 分析建议 */}
            <Col xs={24} md={12}>
              <Card title="分析建议">
                {result.recommendations.relationship_specific_advice && (
                  <Alert
                    message="关系分析"
                    description={result.recommendations.relationship_specific_advice}
                    type="info"
                    showIcon
                    style={{ marginBottom: 16 }}
                  />
                )}
                
                <List
                  header={<div>建议采取的行动</div>}
                  bordered
                  dataSource={result.recommendations.suggested_actions}
                  renderItem={(item, index) => (
                    <List.Item>
                      <Typography.Text mark>[{index + 1}]</Typography.Text> {item}
                    </List.Item>
                  )}
                />
              </Card>
            </Col>
            
            {/* 时间趋势分析 */}
            <Col xs={24}>
              <Card title="时间趋势分析">
                <Timeline mode="left">
                  {result.daily_analysis.map((day, index) => (
                    <Timeline.Item 
                      key={day.date} 
                      color={
                        day.pua_statistics.pua_messages > 0 
                          ? (day.pua_statistics.avg_severity > 0.7 ? 'red' : 'orange') 
                          : 'green'
                      }
                      label={day.date}
                    >
                      <Card 
                        size="small" 
                        title={`${day.date} (${day.count}条消息)`}
                        extra={
                          <Tag color={
                            day.pua_statistics.pua_messages > 0 
                              ? (day.pua_statistics.avg_severity > 0.7 ? 'red' : 'orange')
                              : 'green'
                          }>
                            PUA占比: {Math.round((day.pua_statistics.pua_messages / day.pua_statistics.total_messages) * 100)}%
                          </Tag>
                        }
                      >
                        {day.pua_statistics.pua_messages > 0 ? (
                          <>
                            <Paragraph>
                              <Text strong>检测到PUA消息:</Text> {day.pua_statistics.pua_messages}条
                              <Text style={{ marginLeft: 16 }} strong>平均严重度:</Text> 
                              <Progress 
                                percent={Math.round(day.pua_statistics.avg_severity * 100)}
                                steps={5}
                                strokeColor={day.pua_statistics.avg_severity > 0.7 ? 'red' : 'orange'}
                                size="small"
                                style={{ width: 100, display: 'inline-block', marginLeft: 8 }}
                              />
                            </Paragraph>
                            
                            {Object.keys(day.pua_statistics.categories).length > 0 && (
                              <Paragraph>
                                <Text strong>类别分布:</Text>
                                <div style={{ marginTop: 8 }}>
                                  {Object.entries(day.pua_statistics.categories).map(([category, count]) => (
                                    <Tag key={category} style={{ marginBottom: 4 }}>
                                      {getCategoryName(category)}: {count}次
                                    </Tag>
                                  ))}
                                </div>
                              </Paragraph>
                            )}
                            
                            <Collapse bordered={false} ghost>
                              <Panel 
                                header={`查看${day.detected_pua_messages.length}条PUA消息示例`} 
                                key="1"
                              >
                                <List
                                  size="small"
                                  dataSource={day.detected_pua_messages}
                                  renderItem={message => (
                                    <List.Item
                                      extra={getRiskTag(message.detection_result.risk_level)}
                                    >
                                      <List.Item.Meta
                                        title={
                                          <div>
                                            <Text code>{message.content}</Text>
                                          </div>
                                        }
                                        description={
                                          <div style={{ marginTop: 4 }}>
                                            {message.detection_result.detected_patterns.map((pattern, i) => (
                                              <Tag key={i} color="magenta">
                                                {getCategoryName(pattern.category)}
                                              </Tag>
                                            ))}
                                          </div>
                                        }
                                      />
                                    </List.Item>
                                  )}
                                />
                              </Panel>
                            </Collapse>
                          </>
                        ) : (
                          <Empty description="未检测到PUA内容" image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        )}
                      </Card>
                    </Timeline.Item>
                  ))}
                </Timeline>
              </Card>
            </Col>
          </Row>
        </div>
      )}
    </div>
  );
};

export default PUAConversationAnalysisPage; 